<template>
	<div>
		<el-card shadow="always" :body-style="{ padding: '20px' }">
			<template #header>
				<el-button type="primary" color="#ffde5d" round icon="ele-Edit" @click="addTrademark">添加</el-button>
			</template>
			<!-- card body -->
			<el-table
				:style="{ marginBottom: '30px' }"
				:data="tabelData"
				border
				stripe
			>
				<el-table-column align="center" type="index" label="序号" width="80" />
				<el-table-column
					align="center"
					prop="tmName"
					label="品牌名称"
				></el-table-column>
				<!-- logo -->
				<el-table-column align="center" prop="logoUrl" label="品牌LOGO">
					<!-- 表格作用域插槽的作用域数据row代表当前行完整数据 $index代表当前数据的下标 -->
					<template #default="{ row }">
						<el-image
							:src="row.logoUrl"
							:lazy="true"
							style="height: 60px"
						></el-image>
					</template>
				</el-table-column>
				<!-- 操作按钮  修改和删除 -->
				<el-table-column label="操作" align="center">
					<template #default="{ row }">
						<el-button
							type="warning"
							size="small"
							icon="ele-Edit"
							@click="updateTrademark(row)"
							title="修改品牌信息"
						></el-button>
						<el-button
							type="danger"
							size="small"
							icon="ele-Delete"
							@click="deleteTrademark(row.id)"
							title="删除品牌"
						></el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 翻页器 -->
			<el-pagination
				v-model:page-size="limit"
				:pager-count="5"
				:page-sizes="[3, 5, 8, 10]"
				v-model:current-page="page"
				layout="jumper,prev, pager, next, total,sizes,  "
				:total="total"
			/>
		</el-card>

		<!-- 提示框 -->
		<el-dialog
			v-model="dialogFormShow"
			align-center
			:title="newTrademark.id ? '修改品牌' : '添加品牌'"
		>
		<!-- form组件添加 rules 属性 子组件用prop属性 实现单独校验-->
			<el-form
				center
				label-width="120px"
				:model="newTrademark"
				ref="formEle"
				:rules="rules"
			>
				<el-form-item label="品牌名称" prop="tmName">
					<el-input autocomplete="off" v-model="newTrademark.tmName" />
				</el-form-item>
				<el-form-item label="品牌LOGO" prop="logoUrl">
					<!-- 
						点击上传图片 
						action:请求的url  
						show-file-list:是否显示已上传文件 
						on-success 文件上传成功的钩子
						before-upload 上传文件前的钩子
					-->
					<el-upload
						class="avatar-uploader"
						action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
						:show-file-list="false"
						:on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload"
					>
						<img
							v-if="newTrademark.logoUrl"
							:src="newTrademark.logoUrl"
							class="avatar"
							height="100"
						/>
						<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
					</el-upload>
				</el-form-item>
			</el-form>
			<!-- 是否确定新增和修改 -->
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogFormShow = false">取消</el-button>
					<el-button type="primary" @click="updateOrAddTrademark"
						>确认</el-button
					>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs, watch } from "vue";
// 获取接口
import {
	reqTrademarkList,
	reqAddTrademark,
	reqUpdateTrademark,
	reqDeleteTrademark,
} from "@/api/trademark";

// 引入类型
import type {
	reqTrademarkReturnRecordsType,
	reqTrademarkReturnItemType,
} from "@/api/trademark";

// 引入element里的消息弹窗框
import { ElMessage, ElMessageBox } from "element-plus";
// 引入element里的类型
import type { UploadProps, FormRules, FormInstance } from "element-plus";
// 引入图标
import { Plus, Edit, Delete } from "@element-plus/icons-vue";

// table逻辑
const tabelData = ref<reqTrademarkReturnRecordsType>([]);

// 页码逻辑
// 页码类型
interface pageDateType {
	page: number;
	limit: number;
	total: number;
}

// 页码的数据
const pageDate = ref<pageDateType>({
	page: 1,
	limit: 5,
	total: 100,
});

// 结构出页码的属性
const { page, limit, total } = toRefs(pageDate.value);

// 获取品牌列表
const getTrademarkList = async () => {
	try {
		const res = await reqTrademarkList({
			page: page.value,
			limit: limit.value,
		});
		//把请求回来的值设置给响应数据
		tabelData.value = res.records;
		total.value = res.total;
	} catch (error) {
		return Promise.reject(error);
	}
};

//监听页码的改变 然后重新发送请求
watch([page, limit], () => {
	getTrademarkList();
});

// 初始化
onMounted(() => {
	//调用获取品牌列表的功能函数
	getTrademarkList();
});

// 弹窗逻辑
// 控制弹窗是否显示
const dialogFormShow = ref(false);

// 收集新增品牌的数据
const newTrademark = ref<reqTrademarkReturnItemType>({
	logoUrl: "",
	tmName: "",
	id: 0,
});

// 上传文件成功的钩子函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (
	response,
) => {
	newTrademark.value.logoUrl = response.data;
};

// 上传文件前的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
	// 判断文件的类型是否时图片
	if (rawFile.type !== "image/jpeg") {
		ElMessage.error("Avatar picture must be JPG format!");
		return false;
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error("Avatar picture size can not exceed 2MB!");
		return false;
	}
	return true;
};

// 添加逻辑
const addTrademark = () => {
	// 清空上一次残留的校验信息
	// 关闭校验规则
	formEle.value?.clearValidate()


	dialogFormShow.value = true;
	newTrademark.value = {
		logoUrl: "",
		tmName: "",
		id: 0,
	};
};

// 修改逻辑
const updateTrademark = async (row: reqTrademarkReturnItemType) => {
	// 关闭校验规则
	formEle.value?.clearValidate()

	//显示弹出框
	dialogFormShow.value = true;
	newTrademark.value = { ...row };
};


//整体校验
const formEle = ref<FormInstance>();

// 点击确定 新增或修改
const updateOrAddTrademark = async () => {
	try {
		const res = await formEle.value?.validate()
		if(!res) return
	} catch (error) {
		return
	}
	// 整体校验
	

	try {
		// 根据newTrademark有没有id 确定是新增还是修改
		if (newTrademark.value.id) {
			// 如果有id 是修改
			await reqUpdateTrademark(newTrademark.value);
			ElMessage.success("修改成功");
		} else {
			await reqAddTrademark(newTrademark.value);
			ElMessage.success("新增成功");
			page.value = 1;
		}
		// 关闭弹窗
		dialogFormShow.value = false;
		// 重新请求数据
		getTrademarkList();
	} catch (error) {
		return Promise.reject(error);
	}
};

// 删除品牌
const deleteTrademark = async (id: number) => {
	/* MessageBox 消息弹框 comfirm配置项是弹出的文字框 */
	ElMessageBox.confirm("是否确定删除?", "警告", {
		confirmButtonText: "删除",
		cancelButtonText: "取消",
		type: "warning",
	})
		.then(async () => {
			// 删除
			try {
				await reqDeleteTrademark(id);
				// 重新发请求
				getTrademarkList();
				ElMessage.success("删除成功");
			} catch (error) {
				ElMessage.error("删除失败");
			}
		})
		.catch(() => {
			ElMessage.info("取消删除");
		});
};

// 单独校验规则
const rules = reactive<FormRules>({
	tmName:[{required:true,message:'品牌名称不能为空',trigger:'bulr' }], // 意思依次是 必填 提示语句 失去焦点时触发
	logoUrl: [{ required: true, message: "品牌的logo不能为空", trigger: "blur" }],
})


</script>

<style scoped>

.avatar-uploader .avatar {

  display: block;
}

/* 如果样式不生效  使用深度选择器 >>> */
.avatar-uploader >>> .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader >>> .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-pagination {
	justify-content: center;
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
